package com.cc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cc.comm.responce.PageResult;
import com.cc.comm.util.OrderIdGenerator;
import com.cc.mapper.InventoryMapper;
import com.cc.mapper.ProductsMapper;
import com.cc.mapper.PurchaseOrderDetailsMapper;
import com.cc.model.dto.OrderDTO;
import com.cc.model.dto.OrderQuery;
import com.cc.model.entity.Inventory;
import com.cc.model.entity.Products;
import com.cc.model.entity.PurchaseOrderDetails;
import com.cc.model.entity.PurchaseOrders;
import com.cc.mapper.PurchaseOrdersMapper;
import com.cc.model.vo.OrderDetailVo;
import com.cc.model.vo.OrderVo;
import com.cc.model.vo.SupplierOrderGroupVo;
import com.cc.service.PurchaseOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购订单表 记录采购订单信息 服务实现类
 * </p>
 *
 * @author 晓东√
 * @since 2025-09-19 11:18
 */
@Service
public class PurchaseOrdersServiceImpl extends ServiceImpl<PurchaseOrdersMapper, PurchaseOrders>
        implements PurchaseOrdersService {
    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;
    //引入商品Mapper
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private PurchaseOrderDetailsMapper purchaseOrderDetailsMapper;
    //引入库存Mapper
    @Autowired
    private InventoryMapper inventoryMapper;

    @Override
    @Transactional   //事务
    public void creatOrder(List<OrderDTO> orderDTOS) {
        //生成订单标号
        String orderId = "cg_" + OrderIdGenerator.generateOrderId();
        //1.将orderDTOS转成Map集合
        Map<Integer, Integer> orderMap = orderDTOS.stream().
                collect(Collectors.toMap(OrderDTO::getProductId, OrderDTO::getQuantity));
        //通过productId查询商品信息
        List<Products> products = productsMapper.selectBatchIds(orderMap.keySet());
//        //统计商品总计
//        double totalAmount = products.stream()
//                .mapToDouble(p -> p.getPurchasePrice()
//                        .multiply(BigDecimal.valueOf(orderMap.get(p.getProductId())))
//                        .doubleValue())
//                .sum();
        //对商品通过供应商Id进行分组
        Map<Integer, List<Products>> supplierProducts = products.stream()
                .collect(Collectors.groupingBy(Products::getSupplierId));
        //遍历数据 ，创建采购订单
        supplierProducts.forEach((supplierId, productsList) -> {
            PurchaseOrders purchaseOrders = new PurchaseOrders();
            purchaseOrders.setOrderId(orderId);
            purchaseOrders.setSupplierId(supplierId);
            purchaseOrders.setOrderDate(new Date());
            //统计该供应商的商品总价
            double totalAmount = productsList.stream().mapToDouble(p -> p.getPurchasePrice()
                            .multiply(BigDecimal.valueOf(orderMap.get(p.getProductId())))
                            .doubleValue())
                    .sum();
            purchaseOrders.setTotalAmount(totalAmount);
            //设定订单状态
            purchaseOrders.setStatus(0);
            //添加到数据库
            purchaseOrdersMapper.insert(purchaseOrders);
        });
        //生成采购订单详情
        products.stream().forEach(p -> {
            PurchaseOrderDetails purchaseOrderDetails = new PurchaseOrderDetails();
            purchaseOrderDetails.setOrderId(orderId);
            purchaseOrderDetails.setSupplierId(p.getSupplierId());
            purchaseOrderDetails.setProductId(p.getProductId());
            purchaseOrderDetails.setQuantity(orderMap.get(p.getProductId()));
            purchaseOrderDetails.setUnitPrice(p.getPurchasePrice().doubleValue());
            purchaseOrderDetails.setSubtotal(p.getPurchasePrice()
                    .multiply(BigDecimal.valueOf(orderMap.get(p.getProductId()))).doubleValue());

            purchaseOrderDetailsMapper.insert(purchaseOrderDetails);
        });


    }

    @Override
    public PageResult<OrderVo> OrderPage(OrderQuery orderQuery) {
        //获取父订单
        Page<OrderVo> page = new Page<>(orderQuery.getPageNum(), orderQuery.getPageSize());
        Page<OrderVo> orderVoPage = purchaseOrdersMapper.selectOrderList(page, orderQuery);
        PageResult<OrderVo> pageResult = PageResult.of(orderVoPage);
        //获取子订单
        pageResult.getList().forEach(orderVo -> {
            List<OrderVo> childOrderVos = purchaseOrdersMapper.
                    selectChildOrdersByOrderId(orderVo.getOrderId());

            orderVo.setChildOrderList(childOrderVos);
        });


        return pageResult;
    }

    @Override
    public void updateStatus(String orderId, Integer supplierId) {
        LambdaUpdateWrapper<PurchaseOrders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PurchaseOrders::getOrderId, orderId)
                .eq(PurchaseOrders::getSupplierId, supplierId)
                .set(PurchaseOrders::getStatus, 1)
                .set(PurchaseOrders::getShipment, new Date());
        purchaseOrdersMapper.update(null, updateWrapper);
    }

    @Override
    public void returnGoods(String orderId, Integer supplierId) {
        LambdaUpdateWrapper<PurchaseOrders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PurchaseOrders::getOrderId, orderId)
                .eq(PurchaseOrders::getSupplierId, supplierId)
                .set(PurchaseOrders::getStatus, 3)
                .set(PurchaseOrders::getReturnTime, new Date());
        purchaseOrdersMapper.update(null, updateWrapper);
    }

    @Transactional
    @Override
    public void receive(String orderId, Integer supplierId) {
        //更改状态
        LambdaUpdateWrapper<PurchaseOrders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PurchaseOrders::getOrderId, orderId)
                .eq(PurchaseOrders::getSupplierId, supplierId)
                .set(PurchaseOrders::getStatus, 2)
                .set(PurchaseOrders::getReceiptTime, new Date());
        purchaseOrdersMapper.update(null, updateWrapper);
        //获取订单详情
        List<OrderDetailVo> orderDetailVos = purchaseOrderDetailsMapper.selectOrderDetails(orderId, supplierId);
        //入库
        orderDetailVos.forEach(orderDetailVo -> {
            //获取库存信息
            Inventory inventory = inventoryMapper.selectById(orderDetailVo.getProductId());
            if (inventory == null) {
                inventory = new Inventory();
                inventory.setProductId(orderDetailVo.getProductId());
                inventory.setQuantity(orderDetailVo.getQuantity());
                inventory.setLastUpdate(new Date());
                inventoryMapper.insert(inventory);
            }else {
                inventory.setQuantity(inventory.getQuantity() + orderDetailVo.getQuantity());
                inventory.setLastUpdate(new Date());
                inventoryMapper.updateById(inventory);
            }
        });

    }

    @Override
    public List<SupplierOrderGroupVo> supplierOrderGroup() {
        List<SupplierOrderGroupVo> supplierOrderGroupVos = purchaseOrdersMapper.supplierOrderGroupByMonth();
        return supplierOrderGroupVos;
    }

    @Override
    public List<OrderVo> queryOrderBySupplierIdAndMonth(String supplierId, String month) {
        List<OrderVo> orderVos = purchaseOrdersMapper.queryOrderBySupplierIdAndMonth(supplierId, month);
        return orderVos;
    }
}
